package com.emm.yixun.marketing.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.emm.yixun.basic.service.*;
import com.emm.yixun.common.app.GetNonpaymentListReqDto;
import com.emm.yixun.common.app.GetNonpaymentListResDto;
import com.emm.yixun.common.app.GetNonpaymentNumResDto;
import com.emm.yixun.common.app.GetNonpaymentResDto;
import com.emm.yixun.common.constant.SysConstants;
import com.emm.yixun.common.enums.ResultEnum;
import com.emm.yixun.common.exception.ResponseCode;
import com.emm.yixun.common.model.*;
import com.emm.yixun.common.model.dto.HaveAdvanceRefundDto;
import com.emm.yixun.common.model.dto.HaveReceiveRefundDto;
import com.emm.yixun.common.model.dto.NeedAdvanceRefundDto;
import com.emm.yixun.common.model.dto.NeedAdvanceRefundInfoDto;
import com.emm.yixun.common.model.enums.*;
import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.page.PageUtil;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.common.utils.DateUtils;
import com.emm.yixun.marketing.service.HaveAdvanceRefundServiceFacade;
import com.emm.yixun.marketing.service.HaveReceiveRefundServiceFacade;
import com.emm.yixun.marketing.service.NeedAdvanceRefundServiceFacade;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.jws.WebService;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service("needAdvanceRefundServiceFacade")
@WebService(name = "com.emm.yixun.marketing.service.NeedAdvanceRefundServiceFacade")
public class NeedAdvanceRefundServiceFacadeImpl implements NeedAdvanceRefundServiceFacade {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private NeedAdvanceRefundService needAdvanceRefundService;

	@Autowired
	private SubscribeService subscribeService;

	@Autowired
	private HaveReceiveRefundServiceFacade haveReceiveRefundServiceFacade;

	@Autowired
	private HaveAdvanceRefundServiceFacade haveAdvanceRefundServiceFacade;

	@Autowired
	private DataPermissionService dataPermissionService;
	
	@Autowired
	private PayDepositService payDepositService;
	
	@Autowired
	private SignedService signedService;
	
	@Autowired
	private ReserveAreaService reserveAreaService;
	
	@Autowired
	private UserService userService;

	@Override
	public Response<NeedAdvanceRefundDto> save(NeedAdvanceRefundDto dto) {
		Response<NeedAdvanceRefundDto> response = new Response<NeedAdvanceRefundDto>();
		try {
			if (null == dto) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(),
						ResponseCode.PARAM_INVALID.formatMessage("保存"));
				return response;
			}
			NeedAdvanceRefundDto mDto = needAdvanceRefundService.create(dto);
			if (null == mDto) {
				response.fail("80000", "保存数据错误");
				return response;
			}
			response.success(mDto);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(),
					ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("保存数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<Integer> updateByPrimaryKey(NeedAdvanceRefundDto dto,
			Boolean selective) {
		Response<Integer> response = new Response<Integer>();
		try {
			if (null == selective || null == dto || null == dto.getId()) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(),
						ResponseCode.PARAM_INVALID.formatMessage("更新"));
				return response;
			}

			if (selective) {
				int count = needAdvanceRefundService.update(dto);
				if (count > 0) {
					response.success(Integer.valueOf(count));
				} else {
					response.fail("90001", "更新数据失败");
				}
			} else {
				response.fail("90000", "暂未实现,修改参数selective=true即可");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(),
					ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("更新数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<Integer> deleteByPrimaryKey(Long id) {
		Response<Integer> response = new Response<Integer>();
		try {
			if (null == id) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(),
						ResponseCode.PARAM_INVALID.formatMessage("删除"));
				return response;
			}
			NeedAdvanceRefundDto mDto = new NeedAdvanceRefundDto();
			mDto.setId(id);
			int count = needAdvanceRefundService.destroy(mDto);
			if (count > 0) {
				response.success(Integer.valueOf(count));
			} else {
				response.fail("90001", "删除数据失败");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(),
					ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("删除数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<NeedAdvanceRefund> findById(Long id) {
		Response<NeedAdvanceRefund> response = new Response<NeedAdvanceRefund>();
		try {
			if (null == id) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(),
						ResponseCode.PARAM_INVALID.formatMessage("主键查询"));
				return response;
			}
			NeedAdvanceRefund entity = needAdvanceRefundService.selectById(id);
			if (null == entity) {
				response.fail("90001", "主键查询数据失败");
			} else {
				response.success(entity);
				;
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(),
					ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("主键查询数据错误：{}", e);
		}
		return response;
	}

	@Override
	public ResponseList<NeedAdvanceRefund> findByDto(NeedAdvanceRefundDto dto) {
		ResponseList<NeedAdvanceRefund> response = new ResponseList<NeedAdvanceRefund>();
		try {
			if (null == dto) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(),
						ResponseCode.PARAM_INVALID.formatMessage("查询"));
				return response;
			}
			List<NeedAdvanceRefund> list = needAdvanceRefundService.selectListByDto(dto);

			if (null == list) {
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(),
						ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}

			response.success(list);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(),
					ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Page<NeedAdvanceRefund> findPageByDto(NeedAdvanceRefundDto dto,
			Integer begin, Integer row) {
		Page<NeedAdvanceRefund> response = new Page<NeedAdvanceRefund>();
		try {
			if (null == dto || null == begin || null == row) {
				response.setSuccess(false);
				response.setErrorMsg("参数不合法");
				return response;
			}
			Page<NeedAdvanceRefund> page = needAdvanceRefundService
					.getPageModel(dto, begin, row);
			if (null == page.getRows()) {
				response.setSuccess(false);
				response.setErrorMsg("分页数据不存在");
				return response;
			}
			response = page;
			response.setSuccess(true);
		} catch (Exception e) {
			response.setSuccess(false);
			response.setErrorMsg(ResponseCode.SYSTEM_EXCEPTION
					.getMessageTemplate());
			logger.error("查询分页数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Page<NeedAdvanceRefundInfo> findPageByDtoInfo(
			NeedAdvanceRefundInfoDto dto, Integer begin, Integer row) {
		Page<NeedAdvanceRefundInfo> response = new Page<NeedAdvanceRefundInfo>();
		try {
			if (null == dto || null == begin || null == row) {
				response.setSuccess(false);
				response.setErrorMsg("参数不合法");
				return response;
			}

			String sbsql = " and t.business_type IN (";
			if (!StringUtils.isEmpty(dto.getBusinessType())) {
				String[] receivablesType = dto.getBusinessType().split(",");
				for (int i = 0; i < receivablesType.length; i++) {
					sbsql += receivablesType[i];
					if (i != receivablesType.length - 1) {
						sbsql += ",";
					}
				}
				sbsql = sbsql + ")";
				dto.setBusinessType(sbsql);
			}
			
			//数据权限
			if(SysConstants.openDataPermission){
				String dataPermission = dataPermissionService.dataPermissionCondition(dto.getPermissionUserId(), dto.getResourcesCode(), null, null);
				String [] dataPermissionArr = dataPermission.split(":");
				dto.setDataPermission(dataPermissionArr[1]);
			}

			Page<NeedAdvanceRefundInfo> page = needAdvanceRefundService.getPageModelInfo(dto,begin, row);
			if (null == page.getRows()) {
				response.setSuccess(false);
				response.setErrorMsg("分页数据不存在");
				return response;
			}

			List<NeedAdvanceRefundInfo> list = page.getRows();
			for (int i = 0; i < list.size(); i++) {
				NeedAdvanceRefundInfo info = list.get(i);
				if (info.getBusinessType().equals(BusinessTypeEnum.SIGNED.getNo())) {
					// 签约
					Signed signed = signedService.selectById(info.getRelationId());
					if (signed != null) {
						String code = signed.getSignCode();
						if (StringUtils.isEmpty(code)) {
							code = "";
						}
						info.setRelationCode("签约：" + code);
						if(signed.getCalculateArea() != null){
							info.setCalculatArea(signed.getCalculateArea().toString());
						}
						info.setPrice(signed.getSignPrice());
						info.setTotalPrice(signed.getSignAmount());
					}
				}
				if (!StringUtils.isEmpty(info.getHousingFundType())) {
					info.setRelationType(HousingFundTypeEnum.getByNo(info.getHousingFundType()).getDes());
				}
				BigDecimal reAmout = new BigDecimal("0");
				HaveAdvanceRefundDto haveDto = new HaveAdvanceRefundDto();
				haveDto.setReceivablesId(info.getId());
				haveDto.setDocType(dto.getDocType());
				ResponseList<HaveAdvanceRefund> haveResp = haveAdvanceRefundServiceFacade.findByDto(haveDto);
				if (haveResp.getEntity() != null) {
					List<HaveAdvanceRefund> haveList = haveResp.getEntity();
					for (int l = 0; l < haveList.size(); l++) {
						HaveAdvanceRefund have = (HaveAdvanceRefund) haveList.get(l);
						// 排除手续费
						if (have.getHousingFundType().equals(HousingFundTypeEnum.FUNDTYPE_8.getNo())) {
							continue;
						}
						BigDecimal deductible = have.getDeductibleAmount(); // 抵扣金额
						BigDecimal real = have.getRealAmount(); // 实收金额
						reAmout = reAmout.add(deductible.add(real)); // 已收金额 = 实收金额 + 抵扣金额

						if ("1".equals(info.getDocType())) {
							// 单类型为退款时，查询经办人和经办日期
							// Response<User> user = userServiceFacade.findById(have.getStatementId());
							// if(user.getEntity() != null){
							// info.setStatement_name(user.getEntity().getUserName());
							// }
							// info.setStatement_date(have.getStatementDate());
						}
					}
				}
				info.setReceivedAmount(reAmout); // 已收金额
				info.setUncollectedAmount(info.getTotalReceivablesAmount().subtract(
						info.getReceivedAmount())); // 未收金额 = 总金额 - 已收金额
				// 经办人
				if (info.getCreateUserId() != null) {
					User user = userService.selectById(info.getCreateUserId());
					if (user != null) {
						info.setStatement_name(user.getUserName());
					}
				}
			}
			response = page;
			response.setSuccess(true);
		} catch (Exception e) {
			response.setSuccess(false);
			response.setErrorMsg(ResponseCode.SYSTEM_EXCEPTION
					.getMessageTemplate());
			logger.error("查询分页数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Page<NeedAdvanceRefundInfo> findPageByDtoReport(NeedAdvanceRefundInfoDto dto,
												 Integer begin, Integer row) {
		Page<NeedAdvanceRefundInfo> response = new Page<NeedAdvanceRefundInfo>();
		try {
			if (null == dto || null == begin || null == row) {
				response.setSuccess(false);
				response.setErrorMsg("参数不合法");
				return response;
			}
			Page<NeedAdvanceRefundInfo> page = needAdvanceRefundService.getPageModelReport(dto, begin, row);
			if (null == page.getRows()) {
				response.setSuccess(false);
				response.setErrorMsg("分页数据不存在");
				return response;
			}
			response = page;
			response.setSuccess(true);
		} catch (Exception e) {
			response.setSuccess(false);
			response.setErrorMsg(ResponseCode.SYSTEM_EXCEPTION
					.getMessageTemplate());
			logger.error("查询分页数据错误：{}", e);
		}
		return response;
	}

	@Override
	public ResponseList<NeedAdvanceRefundDto> findNrrfDtoByDto(
			NeedAdvanceRefundDto dto) {
		ResponseList<NeedAdvanceRefundDto> response = new ResponseList<NeedAdvanceRefundDto>();
		try {
			if (null == dto) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(),
						ResponseCode.PARAM_INVALID.formatMessage("查询"));
				return response;
			}
			List<NeedAdvanceRefundDto> list = needAdvanceRefundService
					.selectNrrfDtoListByDto(dto);
			if (null == list) {
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(),
						ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}
			response.success(list);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(),
					ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<NeedAdvanceRefundInfo> findInfoById(Long id) {
		Response<NeedAdvanceRefundInfo> response = new Response<NeedAdvanceRefundInfo>();
		try {
			if (null == id) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(),
						ResponseCode.PARAM_INVALID.formatMessage("主键查询"));
				return response;
			}
			NeedAdvanceRefundInfo entity = needAdvanceRefundService.selectInfoById(id);
			if (null == entity) {
				response.fail("90001", "主键查询数据失败");
			} else {
				response.success(entity);
				;
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(),
					ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("主键查询数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<Boolean> vaildNeedReceive(Long payId, Long subId) {
		Response<Boolean> response = new Response<Boolean>();
		NeedAdvanceRefundDto receiveRefundDto = new NeedAdvanceRefundDto();
		try {
			// 认筹ID不为空的情况有两种:1 认筹转认购 2 认筹转签约
			if (payId != null) {
				receiveRefundDto.setRelationId(payId);
				receiveRefundDto.setBusinessType(BusinessTypeEnum.DEPOSIT.getNo());
			}else if(subId!=null){
				//receiveRefundDto.setBusinessFlag(BusinessFlagEnum);
				receiveRefundDto.setRelationId(subId);
				receiveRefundDto.setBusinessType(BusinessTypeEnum.SUBSCRIBE.getNo());
				receiveRefundDto.setBusinessFlag(BusinessFlagEnum.BUSINESSFLAG_5.getNo());
			}
			receiveRefundDto.setDocType(DocTypeEnum.COLLECTION.getNo());
			NeedAdvanceRefund need = needAdvanceRefundService.selectByDto(receiveRefundDto);
			if(need!=null){
				Response<BigDecimal> haveRep = haveReceiveRefundServiceFacade.findHaveAmount(need.getId());
				//subAmount
				need.setTotalReceivablesAmount(need.getTotalReceivablesAmount());
				if(haveRep.getEntity().compareTo(need.getTotalReceivablesAmount())==0){
					response.setEntity(true);
				}else{
					response.setEntity(false);
					response.setResultMessage("请收齐应收款后在进行操作!");
				}
			}else{
				//没有应收款
				response.setEntity(true);
			}
			
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(),ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("数据查询错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<Integer> deleteByDto(NeedAdvanceRefundDto dto) {
		Response<Integer> response = new Response<Integer>();
		try {
			needAdvanceRefundService.destroy(dto);
		} catch (Exception e) {
			logger.error("deleteByDto error: ", e);
		}
		
		return response;
	}
	
	@Override
	public boolean isDelByDto(NeedAdvanceRefundDto dto){
		boolean flag = false;
		try {
			//先查询是否有待收款记录
			List<NeedAdvanceRefund> list = needAdvanceRefundService.selectListByDto(dto);
			//当查询结果为null时，不需要执行删除方法
			if(list == null || list.size() == 0){
				return true;
			}
			//当有待收款记录时，将待收款记录状态修改为已删除
			for(NeedAdvanceRefund need : list){
				NeedAdvanceRefundDto entity = new NeedAdvanceRefundDto();
				entity.setId(need.getId());
				entity.setDelFlag(DelFlagEnum.DEL.getNo());
				entity.setRemark(dto.getRemark() + "|删除待收款");
				needAdvanceRefundService.update(entity);
			}
			flag = true;
		} catch (Exception e) {
			logger.error("isDelByDto error: ", e);
		}
		return flag;
	}
	
	/**
	 * 签约回款提醒数量
	 */
	@Override
	public Response<Integer> selectNonpaymentNum(NeedAdvanceRefundDto dto, int day) {
		Response<Integer> response=new Response<Integer>();
		try {
			if(null == dto){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("查询"));
				return response;
			}
			//判断权限
			if(SysConstants.openDataPermission){
				String dataPermission = dataPermissionService.dataPermissionCondition(dto.getPermissionUserId(), dto.getResourcesCode(), null, null);
				String [] dataPermissionArr = dataPermission.split(":");
				dto.setDataPermission(dataPermissionArr[1]);
			}
			
			int num = needAdvanceRefundService.selectNonpaymentNum(dto, null, day);
			response.setEntity(num);
			response.setSuccess(true);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询签约回款提醒数量错误：{}",e);
		}
		return response;
	}
	
	/**
	 * 签约回款提醒分页
	 */
	@Override
	public Page<NeedAdvanceRefundInfo> selectNonpaymentPage(NeedAdvanceRefundDto dto, Long projectId, int day, 
			Integer begin, Integer row) {
		Page<NeedAdvanceRefundInfo> response=new Page<NeedAdvanceRefundInfo>();
		try {
			if(null == dto){
				response.setSuccess(false);
				response.setErrorMsg("参数不合法");
			}
			//判断权限
			if(SysConstants.openDataPermission){
				String dataPermission = dataPermissionService.dataPermissionCondition(dto.getPermissionUserId(), dto.getResourcesCode(), null, null);
				String [] dataPermissionArr = dataPermission.split(":");
				dto.setDataPermission(dataPermissionArr[1]);
			}
			
			response = needAdvanceRefundService.selectNonpaymentPage(dto, projectId, day, begin, row);
			List<NeedAdvanceRefundInfo> list = response.getRows();
			for (int i = 0; i < list.size(); i++) {
				NeedAdvanceRefundInfo info = (NeedAdvanceRefundInfo) list.get(i);
				//处理明细数据
				selectNonpaymentDetail(info);
			}
			response.setSuccess(true);
		} catch (Exception e) {
			response.setErrorMsg("系统异常");
			response.setSuccess(false);
			logger.error("签约回款提醒分页查询错误：{}",e);
		}
		return response;
	}
	
	/**
	 * 签约回款提醒列表
	 */
	@Override
	public ResponseList<NeedAdvanceRefundInfo> selectNonpaymentList(NeedAdvanceRefundDto dto, Long projectId, int day) {
		ResponseList<NeedAdvanceRefundInfo> response=new ResponseList<NeedAdvanceRefundInfo>();
		try {
			if(null == dto){
				response.setSuccess(false);
				response.setResultMessage("参数不合法");
			}
			//判断权限
			if(SysConstants.openDataPermission){
				String dataPermission = dataPermissionService.dataPermissionCondition(dto.getPermissionUserId(), dto.getResourcesCode(), null, null);
				String [] dataPermissionArr = dataPermission.split(":");
				dto.setDataPermission(dataPermissionArr[1]);
			}
			
			List<NeedAdvanceRefundInfo> list = needAdvanceRefundService.selectNonpaymentList(dto, projectId, day);
			for (int i = 0; i < list.size(); i++) {
				NeedAdvanceRefundInfo info = (NeedAdvanceRefundInfo) list.get(i);
				//处理明细数据
				selectNonpaymentDetail(info);
			}
			response.setEntity(list);
			response.setSuccess(true);
		} catch (Exception e) {
			response.setResultMessage("系统异常");
			response.setSuccess(false);
			logger.error("查询签约回款提醒列表错误：{}",e);
		}
		return response;
	}
	
	/**
	 * 列表中的数据进行处理
	 * @param info
	 * @return
	 */
	private NeedAdvanceRefundInfo selectNonpaymentDetail(NeedAdvanceRefundInfo info){
		//获取房款类型
		if (!StringUtils.isEmpty(info.getHousingFundType())) {
			info.setRelationType(HousingFundTypeEnum.getByNo(info.getHousingFundType()).getDes());
		}
		//获取客户性别
		if(!StringUtils.isEmpty(info.getCustomerSex())) {
			info.setCustomerSex(CustomerSexEnum.getByNo(info.getCustomerSex()).getDes());
		}
		//计算已收金额与未收金额
		BigDecimal reAmout = new BigDecimal("0");
		HaveReceiveRefundDto haveDto = new HaveReceiveRefundDto();
		haveDto.setReceivablesId(info.getId());
		haveDto.setDocType(info.getDocType());
		ResponseList<HaveReceiveRefund> haveResp = haveReceiveRefundServiceFacade
				.findByDto(haveDto);
		if (haveResp.getEntity() != null) {
			List<HaveReceiveRefund> haveList = haveResp.getEntity();
			for (int l = 0; l < haveList.size(); l++) {
				HaveReceiveRefund have = (HaveReceiveRefund) haveList.get(l);
				// 排除手续费
				if (have.getHousingFundType().equals(HousingFundTypeEnum.FUNDTYPE_8.getNo()))
					continue;
				BigDecimal deductible = have.getDeductibleAmount(); // 抵扣金额
				BigDecimal real = have.getRealAmount(); // 实收金额
				reAmout = reAmout.add(deductible.add(real)); // 已收金额 = 实收金额 + 抵扣金额
			}
		}
		info.setReceivedAmount(reAmout); // 已收金额
		info.setUncollectedAmount(info.getTotalReceivablesAmount().subtract(
				info.getReceivedAmount())); // 未收金额 = 总金额 - 已收金额
		
		return info;
	}
	
	/**
	 * 签约回款提醒数量(app)
	 */
	@Override
	public GetNonpaymentNumResDto selectNonpaymentNumByApp(GetNonpaymentListReqDto reqDto) {
		GetNonpaymentNumResDto resDto = new GetNonpaymentNumResDto();
		try {
			String userId = reqDto.getUserId();
			if(StringUtils.isEmpty(userId)) {
				resDto.setErrorMsg("经纪人ID不能为空");
				resDto.setErrorCode("0000");
				resDto.setResult(ResultEnum.FAILURE.getNo());
				return resDto;
			}
			Long merchantId = reqDto.getMerchantId();
			if(merchantId == null) {
				resDto.setErrorMsg("商户ID不能为空");
				resDto.setErrorCode("0000");
				resDto.setResult(ResultEnum.FAILURE.getNo());
				return resDto;
			}
			Long projectId = reqDto.getProjectId();
			if(projectId == null) {
				resDto.setErrorMsg("项目ID不能为空");
				resDto.setErrorCode("0000");
				resDto.setResult(ResultEnum.FAILURE.getNo());
				return resDto;
			}
			
			NeedAdvanceRefundDto dto = new NeedAdvanceRefundDto();
			dto.setMerchantId(merchantId);
			//判断权限
			if(SysConstants.openDataPermission){
				String dataPermission = dataPermissionService
						.dataPermissionCondition(Long.parseLong(reqDto.getUserId()), "menu_0003_0001", null, null);
				String [] dataPermissionArr = dataPermission.split(":");
				dto.setDataPermission(dataPermissionArr[1]);
			}
			int num = needAdvanceRefundService.selectNonpaymentNum(dto, projectId, 10);
			resDto.setNonpaymentNum(num);
			resDto.setResult(ResultEnum.SUCCESS.getNo());
		} catch (Exception e) {
			resDto.setErrorMsg("签约回款提醒查询失败");
			resDto.setErrorCode("9999");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			logger.error("签约回款提醒数量查询错误：{}",e);
		}
		return resDto;
	}
	
	/**
	 * 签约回款提醒分页(app)
	 */
	@Override
	public GetNonpaymentListResDto selectNonpaymentPageByApp(GetNonpaymentListReqDto reqDto) {
		GetNonpaymentListResDto resDto = new GetNonpaymentListResDto();
		try {
			Integer begin = reqDto.getPageNumber();
			Integer row = reqDto.getPageSize();
			
			NeedAdvanceRefundDto dto = new NeedAdvanceRefundDto();
			dto.setMerchantId(reqDto.getMerchantId());
			dto.setCustomerName(reqDto.getQueryConditions()); //设置查询条件
			//判断权限
			if(SysConstants.openDataPermission){
				String dataPermission = dataPermissionService
						.dataPermissionCondition(Long.parseLong(reqDto.getUserId()), "menu_0003_0001", null, null);
				String [] dataPermissionArr = dataPermission.split(":");
				dto.setDataPermission(dataPermissionArr[1]);
			}
			Page<NeedAdvanceRefundInfo> response = needAdvanceRefundService
					.selectNonpaymentPage(dto, reqDto.getProjectId(), 10, 
							PageUtil.begin(begin, row), row);
			List<NeedAdvanceRefundInfo> list = response.getRows();
			
			List<GetNonpaymentResDto> nonpaymentList = new ArrayList<GetNonpaymentResDto>();
			for (int i = 0; i < list.size(); i++) {
				NeedAdvanceRefundInfo info = (NeedAdvanceRefundInfo) list.get(i);
				//处理明细数据
				nonpaymentList.add(selectNonpaymentDetailByApp(info));
			}
			resDto.setNonpaymentList(nonpaymentList);
			resDto.setPageNumber(response.getPageNumber());
			resDto.setPageSize(response.getPageSize());
			resDto.setTotalPage(response.getTotalPages());
			resDto.setTotalCount(response.getTotal());
			resDto.setResult(ResultEnum.SUCCESS.getNo());
		} catch (Exception e) {
			resDto.setErrorMsg("签约回款提醒查询失败");
			resDto.setErrorCode("9999");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			logger.error("签约回款提醒分页查询错误：{}",e);
		}
		return resDto;
	}
	
	/**
	 * 列表中的数据进行处理(app)
	 * @param info
	 * @return
	 */
	private GetNonpaymentResDto selectNonpaymentDetailByApp(NeedAdvanceRefundInfo info){
		GetNonpaymentResDto resDto = new GetNonpaymentResDto();
		resDto.setCustomerName(info.getCustomer_name());
		resDto.setCustomerPhone(info.getCustomerPhone());
		resDto.setReceivablesDate(DateUtils.formatDate(info.getReceivablesDate(), "yyyy-MM-dd"));
		resDto.setReceivablesDay(info.getReceivablesDay());
		resDto.setCombinedName(info.getCombined_name());
		resDto.setUserName(info.getUserName());
		//计算已收金额与未收金额
		BigDecimal reAmout = new BigDecimal("0");
		HaveReceiveRefundDto haveDto = new HaveReceiveRefundDto();
		haveDto.setReceivablesId(info.getId());
		haveDto.setDocType(info.getDocType());
		ResponseList<HaveReceiveRefund> haveResp = haveReceiveRefundServiceFacade
				.findByDto(haveDto);
		if (haveResp.getEntity() != null) {
			List<HaveReceiveRefund> haveList = haveResp.getEntity();
			for (int l = 0; l < haveList.size(); l++) {
				HaveReceiveRefund have = (HaveReceiveRefund) haveList.get(l);
				// 排除手续费
				if (have.getHousingFundType().equals(HousingFundTypeEnum.FUNDTYPE_8.getNo()))
					continue;
				BigDecimal deductible = have.getDeductibleAmount(); // 抵扣金额
				BigDecimal real = have.getRealAmount(); // 实收金额
				reAmout = reAmout.add(deductible.add(real)); // 已收金额 = 实收金额 + 抵扣金额
			}
		}
		resDto.setUncollectedAmount(info.getTotalReceivablesAmount()
				.subtract(reAmout)); // 未收金额 = 总金额 - 已收金额
		return resDto;
	}

	@Override
	public Response<Integer> getOverduePaymentListCount(NeedAdvanceRefundDto dto) {
		Response<Integer> response=new Response<>();
		try {
			if(null == dto){
				response.setSuccess(false);
				response.setResultMessage("参数不合法");
			}
			//判断权限
			if(SysConstants.openDataPermission){
				String dataPermission = dataPermissionService.dataPermissionCondition(dto.getPermissionUserId(), dto.getResourcesCode(), null, null);
				String [] dataPermissionArr = dataPermission.split(":");
				dto.setDataPermission(dataPermissionArr[1]);
			}

			int count = needAdvanceRefundService.getOverduePaymentListCount(dto);
			response.setEntity(count);
			response.setSuccess(true);
		} catch (Exception e) {
			response.setResultMessage("系统异常");
			response.setSuccess(false);
			logger.error("签约回款提醒分页查询错误：{}",e);
		}
		return response;
	}

	@Override
	public Page<NeedAdvanceRefundInfo> getOverduePaymentPageModel(NeedAdvanceRefundDto dto, Integer begin, Integer row) {
		Page<NeedAdvanceRefundInfo> response=new Page<>();
		try {
			if(null == dto){
				response.setSuccess(false);
				response.setErrorMsg("参数不合法");
			}
			//判断权限
			if(SysConstants.openDataPermission){
				String dataPermission = dataPermissionService.dataPermissionCondition(dto.getPermissionUserId(), dto.getResourcesCode(), null, null);
				String [] dataPermissionArr = dataPermission.split(":");
				dto.setDataPermission(dataPermissionArr[1]);
			}

			Page<NeedAdvanceRefundInfo> page = needAdvanceRefundService.getOverduePaymentPageModel(dto, begin, row);
			response = page;
			response.setSuccess(true);
		} catch (Exception e) {
			response.setSuccess(false);
			response.setErrorMsg("系统异常");
			logger.error("签约回款提醒分页查询错误：{}",e);
		}
		return response;
	}
}
